package com.sunxyz.datasummary.application;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.sunxyz.datasummary.domain.Demo;
import com.sunxyz.datasummary.domain.DemoRepository;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2018/6/25
 **/
@Service
public class DemoService {

    @Autowired
    private DemoRepository repository;

    public void importExcel(InputStream excel) {
        List<DemoExcelDTO> demoExcelDTOS = null;
        try {
            demoExcelDTOS = ExcelImportUtil.importExcel(excel,DemoExcelDTO.class,new ImportParams());
        } catch (Exception e) {
            e.printStackTrace();
        }
        repository.saveAll(demoExcelDTOS.stream().map(this::toDomain).collect(Collectors.toList()));
    }

    public Workbook exportExcel(List<Demo> demoList) {
        List<DemoExcelDTO> list = demoList.stream().map(this::toDTO).collect(Collectors.toList());
        return ExcelExportUtil.exportExcel(new ExportParams(), DemoExcelDTO.class, list);
    }

    private DemoExcelDTO toDTO(Demo demo) {
        return new DemoExcelDTO(
                demo.getDemo()
        );
    }

    private Demo toDomain(DemoExcelDTO dto){
        return new Demo().setDemo(dto.getDemo());
    }
}
